/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.registration.business.security.boundary;

import it.polimi.registration.business.security.entity.Group;
import it.polimi.registration.business.security.entity.Users;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author miglie
 */
@Stateless
public class UsersManager {

    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;

    public void save(Users users) {
        users.setGroupName(Group.USERS);
        em.persist(users);
    }

    public void unregister() {
        em.remove(getLoggedUsers());
    }

    public Users getLoggedUsers() {
        return em.find(Users.class, principal.getName());
    }
    
    public List<Users> getListUsers()
    {
        Query query = em.createQuery("Select u From Users u Where u.email!= :users");
        query.setParameter("users", this.getLoggedUsers().getEmail());
        List<Users> result = new ArrayList<>(query.getResultList());
        return result ;
  }
    
    public Users findByMail(String mail) {

        Query query;
        query = em.createQuery("SELECT u FROM Users u WHERE u.email= :mail ").setParameter("mail", mail);

        List<Users> users = query.getResultList();
        if (!users.isEmpty()) {
            return users.get(0);
        }
        return null;

    }
    
    public Boolean checkExistingUser(String mail) {

        Query query;
        query = em.createQuery("SELECT u FROM Users u WHERE u.email= :mail ").setParameter("mail", mail);

        List<Users> users = query.getResultList();
        if (users.isEmpty()) {
            return false;
        }
        else
            return true;

    }
    
}
